<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Input &amp; output in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, Input &amp; output C#, .NET, Mono, programming, language">
<meta name="description" content="This part of the C# tutorial covers input &amp; output.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Input &amp; output</h1>

<p>
This chapter is dedicated to input &amp; output in C#. 
The input &amp; output in C# is based on streams.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
Streams are objects to work with input/output. A stream is an abstraction
of a sequence of bytes, such as a file, an input/output device,
an inter-process communication pipe, or a TCP/IP socket. In C#,
we have a <b class="keyword">Stream</b> class, that is an abstract class
for all streams. There are additional classes that derive from the Stream
class and make the programming a lot easier.
</p>

<h2>MemoryStream</h2>

<p>
A <code>MemoryStream</code> is a stream which works with 
data in a computer memory. 
</p>

<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {

        try
        {
            Stream ms = new MemoryStream(6);

            ms.WriteByte(9);
            ms.WriteByte(11);
            ms.WriteByte(6);
            ms.WriteByte(8);
            ms.WriteByte(3);
            ms.WriteByte(7);

            ms.Position = 0;

            int rs;
            rs = ms.ReadByte();

            do 
            {
                Console.WriteLine(rs);
                rs = ms.ReadByte();
            } while (rs != -1);

            ms.Close();

        } catch (IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
We write six numbers to a memory with a <code>MemoryStream</code>.
Then we read those numbers and print them to the console. 
</p>

<pre class="explanation">
Stream ms = new MemoryStream(6);
</pre>

<p>
The line creates and initializes a <code>MemoryStream</code> 
object with a capacity of six bytes. 
</p>

<pre class="explanation">
ms.Position = 0;
</pre>

<p>
We set the position of the cursor in the stream to 
the beginning using the <code>Position</code> property.
</p>

<pre class="explanation">
ms.WriteByte(9);
ms.WriteByte(11);
ms.WriteByte(6);
...
</pre>

<p>
The <code>WriteByte()</code> method writes a byte to the current 
stream at the current position.
</p>

<pre class="explanation">
do 
{
    Console.WriteLine(rs);
    rs = ms.ReadByte();
} while (rs != -1);
</pre>

<p>
Here we read all bytes from the stream and print them to the console. 
</p>

<pre class="explanation">
ms.Close();
</pre>

<p>
Finally, we close the stream.
</p>

<pre>
$ ./memory.exe 
9
11
6
8
3
7
</pre>

<p>
Output of the example. 
</p>


<h2>StreamReader &amp; StreamWriter</h2>

<p>
<b class="keyword">StreamReader</b> reads characters from a byte stream. 
It defaults to UTF-8 encoding. <b class="keyword">StreamWriter</b> writes
characters to a stream in a particular encoding. 
</p>


<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {
         
       try
       {
           StreamReader stream = new StreamReader("languages");
           Console.WriteLine(stream.ReadToEnd());

           stream.Close();
       } catch (IOException e)
       {
           Console.WriteLine("Cannot read file.");
           Console.WriteLine(e.Message);
       }
    }
}
</pre>

<p>
We have a file called languages. We read characters from that
file and print them to the console. 
</p>

<pre class="explanation">
StreamReader stream = new StreamReader("languages");
</pre>

<p>
The <code>StreamReader</code> takes a file name as a
parameter.
</p>

<pre class="explanation">
Console.WriteLine(stream.ReadToEnd());
</pre>

<p>
The <code>ReadToEnd()</code> method reads all characters
to the end of the stream. 
</p>


<pre>
$ cat languages 
Python
Visual Basic
PERL
Java
C
C#
$ ./readfile.exe 
Python
Visual Basic
PERL
Java
C
C#
</pre>

<p>
We have a languages file in the current directory. We print all lines
of the file to the console. 
</p>

<hr class="btm">

<p>
In the next example, we will be counting lines. 
</p>

<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {

        int count = 0;

        try
        {           
           StreamReader stream = new StreamReader("languages");

           while(stream.ReadLine() != null)
           {
               count++;
           }

           Console.WriteLine("There are {0} lines", count);

           stream.Close();

        } catch (IOException e)
        {
            Console.WriteLine("Cannot read file.");
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
Counting lines in a file. 
</p>

<pre class="explanation">
while(stream.ReadLine() != null)
{
    count++;
}
</pre>

<p>
In the while loop, we read a line from the stream with
the <code>ReadLine()</code> method. It returns a
line from the stream or null if the end of the input 
stream is reached.
</p>

<hr class="btm">

<p>
An example with <code>StreamWriter</code> follows.
It is a class used for character output.
</p>

<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {

        try 
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter swriter = new StreamWriter(ms);

            swriter.Write("ZetCode, tutorials for programmers.");
            swriter.Flush();
                    
            ms.Position = 0;
            StreamReader sreader = new StreamReader(ms);
            Console.WriteLine(sreader.ReadToEnd());

            swriter.Close();
            sreader.Close();

        } catch (IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
In the preceding example, we write characters to the memory.
</p>

<pre class="explanation">
MemoryStream ms = new MemoryStream();
</pre>

<p>
A <code>MemoryStream</code> is created. It is a stream whose 
backing store is memory.
</p>

<pre class="explanation">
StreamWriter swriter = new StreamWriter(ms);
</pre>

<p>
A <code>StreamWriter</code> class takes a
memory stream as a parameter. This way, we are going
to write characters to memory stream.
</p>

<pre class="explanation">
swriter.Write("ZetCode, tutorials for programmers.");
swriter.Flush();
</pre>

<p>
We write some text to the writer. The <code>Flush()</code>
clears all buffers for the current writer and causes any buffered data
to be written to the underlying stream.
</p>

<pre class="explanation">
ms.Position = 0;
</pre>

<p>
We set the current position within the stream to the
beginning.
</p>


<pre class="explanation">
StreamReader sreader = new StreamReader(ms);
Console.WriteLine(sreader.ReadToEnd());
</pre>

<p>
Now we create an instance of the stream reader and
read everything we have previously written.
</p>


<h2>FileStream</h2>

<p>
A <code>FileStream</code> class uses a stream on a file on
the filesystem. This class can be used to read from files, 
write to files, open them and close them. 
</p>

<pre class="code">
using System;
using System.IO;
using System.Text;

public class CSharpApp
{
    static void Main() {

        try
        {
            FileStream fstream = new FileStream("author", FileMode.Append);
            byte[] bytes = new UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский");

            fstream.Write(bytes, 0, bytes.Length);
            fstream.Close();
        } catch (IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
We write some text in Russian azbuka to the file called author
in the current working directory.
</p>

<pre class="explanation">
using System.Text;
</pre>

<p>
We need the <code>System.Text</code> namespace for the <code>UTF8Encoding</code>
class.
</p>

<pre class="explanation">
FileStream fstream = new FileStream("author", FileMode.Append);
</pre>

<p>
A <code>FileStream</code> object is created. The second
parameter is a mode, in which the file is opened. 
The append mode opens the file if it exists and seeks to the end 
of the file, or creates a new file.
</p>

<pre class="explanation">
byte[] bytes = new UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский");
</pre>

<p>
We create an array of bytes from text in russian azbuka. 
</p>

<pre class="explanation">
fstream.Write(bytes, 0, bytes.Length);
</pre>

<p>
We write the bytes to the file stream. 
</p>

<pre>
$ cat author 
Фёдор Михайлович Достоевский
</pre>

<p>
We show the contents of the author file.
</p>


<h2>XmlTextReader</h2>

<p>
We can use streams to read xml data. The <code>
XmlTextReader</code> is the class to read xml files in C#.
The class is forward-only and read-only. 
</p>

<p>
We have the following xml test file. 
</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;languages&gt;
    &lt;language&gt;Python&lt;/language&gt;
    &lt;language&gt;Ruby&lt;/language&gt;   
    &lt;language&gt;Javascript&lt;/language&gt;
    &lt;language&gt;C#&lt;/language&gt;
&lt;/languages&gt;
</pre>


<pre class="code">
using System;
using System.IO;
using System.Xml;

public class CSharpApp
{
    static void Main() {
       
        string file = "languages.xml";
      
        try
        {
            XmlTextReader xreader = new XmlTextReader(file);

            xreader.MoveToContent();

            while (xreader.Read())
            {
                switch (xreader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.Write(xreader.Name + ": ");
                        break;
                    case XmlNodeType.Text:
                        Console.WriteLine(xreader.Value); 
                        break;
                }
            }
 
            xreader.Close();
 
        } catch (IOException e)
        {
            Console.WriteLine("Cannot read file.");
            Console.WriteLine(e.Message);
        } catch (XmlException e)
        {
            Console.WriteLine("XML parse error");
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
This C# program reads data from the previously
specified xml file and prints it to the terminal. 
</p>

<pre class="explanation">
using System.Xml;
</pre>

<p>
We import the <code>System.Xml</code> namespace, which contains 
classes related to Xml reading and writing.
</p>

<pre class="explanation">
XmlTextReader xreader = new XmlTextReader(file);
</pre>

<p>
An <code>XmlTextReader</code> object is created. It is a reader 
that provides fast, non-cached, forward-only access to XML data.
It takes the file name as a parameter. 
</p>

<pre class="explanation">
xreader.MoveToContent();
</pre>

<p>
The <code>MoveToContent()</code> method moves to the
actual content of the xml file. 
</p>

<pre class="explanation">
while (xreader.Read())
</pre>

<p>
This line reads the next node from the stream. The
<code>Read()</code> method returns false, if there are no more
nodes left.
</p>

<pre class="explanation">
case XmlNodeType.Element:
    Console.Write(xreader.Name + ": ");
    break;
case XmlNodeType.Text:
    Console.WriteLine(xreader.Value); 
    break;
</pre>

<p>
Here we print the element name and element text.
</p>

<pre class="explanation">
} catch (XmlException e)
{
    Console.WriteLine("XML parse error");
    Console.WriteLine(e.Message);
}
</pre>

<p>
We check for xml parse error.
</p>

<pre>
$ ./readxml.exe 
language: Python
language: Ruby
language: Javascript
language: C#
</pre>

<p>
Output of example.
</p>

<h2>Files and directories</h2>

<p>
The .NET framework provides other classes that we can 
use to work with files and directories. 
</p>

<p>
A <code>File</code> class is a higher level class that
has static methods for file creation, deletion, copying, moving and opening. 
These methods make the job easier. 
</p>

<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {

       try
       {        
            StreamWriter sw = File.CreateText("cars");

            sw.WriteLine("Hummer");
            sw.WriteLine("Skoda");
            sw.WriteLine("BMW");
            sw.WriteLine("Volkswagen");
            sw.WriteLine("Volvo");

            sw.Close();

       } catch (IOException e)
       {
           Console.WriteLine("IO error");
           Console.WriteLine(e.Message);
       }
    }
}
</pre>

<p>
In the example, we create a cars file and write
some car names into it. 
</p>

<pre class="explanation">
StreamWriter sw = File.CreateText("cars");
</pre>

<p>
The <code>CreateText()</code> method creates or 
opens a file for writing UTF-8 encoded text. It returns
a <code>StreamWriter</code> object. 
</p>

<pre class="explanation">
sw.WriteLine("Hummer");
sw.WriteLine("Skoda");
...
</pre>

<p>
We write two lines to the stream. 
</p>

<pre>
$ cat cars
Hummer
Skoda
BMW
Volkswagen
Volvo
</pre>

<p>
We have successfully written five car names to a
cars file. 
</p>

<hr class="btm">

<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {

       try
       {        
            if (File.Exists("cars"))
            {
                Console.WriteLine(File.GetCreationTime("cars"));
                Console.WriteLine(File.GetLastWriteTime("cars"));
                Console.WriteLine(File.GetLastAccessTime("cars"));
            }

            File.Copy("cars", "newcars");

       } catch (IOException e)
       {
           Console.WriteLine("IO error");
           Console.WriteLine(e.Message);
       }
    }
}
</pre>

<p>
In the second example, we show other five static methods of the
File class. 
</p>

<pre class="explanation">
if (File.Exists("cars"))
</pre>

<p>
The <code>Exists()</code> method determines whether 
the specified file exists. 
</p>

<pre class="explanation">
Console.WriteLine(File.GetCreationTime("cars"));
Console.WriteLine(File.GetLastWriteTime("cars"));
Console.WriteLine(File.GetLastAccessTime("cars"));
</pre>

<p>
We get creation time, last write time and last access
time of the specified file. 
</p>

<pre class="explanation">
File.Copy("cars", "newcars");
</pre>

<p>
The <code>Copy()</code> method copies the file. 
</p>

<pre>
$ ./copyfile.exe 
10/16/2010 11:48:54 PM
10/16/2010 11:48:54 PM
10/16/2010 11:48:57 PM
</pre>

<p>
Output of the example on my system.
</p>

<hr class="btm">

<p>
The <code>System.IO.Directory</code> is a class, which
has static methods for creating, moving, and enumerating through 
directories and subdirectories.
</p>

<pre class="code">
using System;
using System.IO;


public class CSharpApp
{
    static void Main() {

        try
        {
            Directory.CreateDirectory("temp");
            Directory.CreateDirectory("newdir");
            Directory.Move("temp", "temporary");
        } catch (IOException e)
        {
            Console.WriteLine("Cannot create directories");
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
We will use two methods from the above mentioned object. 
We create two directories and rename one of the created ones.
</p>

<pre class="explanation">
Directory.CreateDirectory("temp");
</pre>

<p>
The <code>CreateDirectory()</code> method creates a new
directory.
</p>

<pre class="explanation">
Directory.Move("temp", "temporary");
</pre>

<p>
The <code>Move()</code> method gives a specified
directory a new name.
</p>

<hr class="btm">

<p>
The <code>DirectoryInfo</code> and <code>Directory</code> have 
methods for creating, moving, and enumerating through directories and subdirectories.
</p>

<pre class="code">
using System;
using System.IO;

public class CSharpApp
{
    static void Main() {

        try 
        {
            DirectoryInfo dir = new DirectoryInfo("../io");

            string[] files = Directory.GetFiles("../io");
            DirectoryInfo[] dirs = dir.GetDirectories();
            
            foreach(DirectoryInfo subDir in dirs)
            {
                Console.WriteLine(subDir.Name);
            }

            foreach(string fileName in files)
            {
                Console.WriteLine(fileName);
            }

        } catch (IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
</pre>

<p>
We use the <code>DirectoryInfo</code> class to traverse a
specific directory and print its contents. 
</p>

<pre class="explanation">
DirectoryInfo dir = new DirectoryInfo("../io");
</pre>

<p>
We will show the contents of this directory (io).
</p>

<pre class="explanation">
string[] files = Directory.GetFiles("../io");
</pre>

<p>
We get all files of the io directory using the static
<code>GetFiles()</code> method.
</p>

<pre class="explanation">
DirectoryInfo[] dirs = dir.GetDirectories();
</pre>

<p>
We get all directories. 
</p>


<pre class="explanation">
foreach(DirectoryInfo subDir in dirs)
{
    Console.WriteLine(subDir.Name);
}
</pre>

<p>
Here we loop through directories and print their names
to the console. 
</p>

<pre class="explanation">
foreach(string fileName in files)
{
    Console.WriteLine(fileName);
}
</pre>

<p>
Here we loop through the array of files and print
their names to the console. 
</p>

<pre>
$ ./showcontents.exe 
newdir
temporary
../io/author
../io/cars
../io/cars.cs
../io/cars.cs~
../io/cars.exe
...
</pre>

<p>
Output of the example. 
</p>

<p>
In this chapter, we have covered Input/Output operations in C#. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 17, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

